package com.yopuo.web.config.oss;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yopuo.common.config.OssQiniuConfig;
import com.yopuo.common.exception.oss.OssException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 七牛云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class QiniuCloudStorageService extends CloudStorageService {

    private UploadManager uploadManager;
    private String token;
    private Auth auth;

    public QiniuCloudStorageService(){
        //初始化
        init();
    }

    private void init(){
        auth = Auth.create(OssQiniuConfig.getAccessKey(), OssQiniuConfig.getSecretKey());
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        token = auth.uploadToken(OssQiniuConfig.getBucketName());
    }

    @Override
    public String upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        } catch (Exception e) {
            throw new OssException("上传文件失败，请核对七牛配置信息", e);
        }

        return OssQiniuConfig.getDomain() + "/" + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new OssException("上传文件失败", e);
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(OssQiniuConfig.getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(OssQiniuConfig.getPrefix(), suffix));
    }

    /**
     * 通过发送http get 请求获取文件资源
     * @param targetUrl
     * @return
     */
    public void download(String targetUrl) {
        //获取downloadUrl
        String downloadUrl = auth.privateDownloadUrl(targetUrl);
        //本地保存路径
        String filePath = "/Users/xuhuanchao/Documents/admin/download/";
        OkHttpClient client = new OkHttpClient();
        Request req = new Request.Builder().url(downloadUrl).build();
        okhttp3.Response resp = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if(resp.isSuccessful()) {
                ResponseBody body = resp.body();
                InputStream is = body.byteStream();
                byte[] data = readInputStream(is);
                File imgFile = new File(filePath);
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();
            }
        } catch (IOException e) {
            throw new OssException("下载文件失败", e);
        }
    }

    /**
     * 读取字节输入流内容
     * @param is
     * @return
     */
    private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }
}
